<template>
	<view class="connect" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar></nav-bar>
		<view class="device_info">
			<view class="title">
				{{ ble.state == 0 ? '仪器已连接' : '账号绑定信息' }}
			</view>
			<view class="device_c">
				<image :src="ble.state == 0 ? img_2 : img_1" class="device_i" />
				<view class="device_name">
					蓝牙名: {{ ble.state == 0 ? ble.defaultInfo.name : deviceInfo.bluetoothName }}
				</view>
				<view class="info">
					<view class="battery" v-if="ble.state == 0">
						<text
							style="padding-right: 8rpx;">{{ ble.defaultInfo.battery ? `${ble.defaultInfo.battery}%`  : '' }}</text>
						<u-image width="44rpx" height="26rpx" :showMenuByLongpress="false"
							:src="myGetBatteryIcon(ble.defaultInfo.battery)" :showLoading="false" :showError="false"
							:lazy-load="true"></u-image>
					</view>
					<view class="line"></view>
					<view class="mac">
						地址: {{ ble.state == 0 ? ble.defaultInfo.mac : deviceInfo.deviceMac }}
					</view>
				</view>
				<view class="version">
					版本号: {{ ble.defaultInfo.version ? `${ble.defaultInfo.version}` : '' }}
				</view>
			</view>
			<view class="connect_btn" @click="$u.throttle(checkBleStatus, 1500)" v-if="ble.state < 0">
				连接仪器
			</view>
			<view class="next_step" @click="$u.throttle(next, 1500)" v-else>
				下一步
			</view>
			<view class="unbind" @click="$u.throttle(unbind, 1500)">
				解绑
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDeviceByUser,
		unbindDevice,
		findBodyMegByUserId,
		findFirstRer,
		getDetailsByUser
	} from '@/api/index.js'
	import {
		mapState
	} from 'vuex'
	import {
		getBatteryIcon
	} from '@/utils/utils.js'
	const BLE = require('@/utils/ble.js');
	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync('userId'),
				img_1: 'http://oss.antaimedical.com/images/static/2024/08/66b47bdbe4b09217821c0fa97zzIw6raL2Bxc2f498c39041f05b1284c3871aab3e21.png',
				img_2: 'http://oss.antaimedical.com/images/static/2024/08/66b47bc1e4b000d2c606b524bblrMJK2gq935a3581f5f3a72a294dcfd449f2b1e19c.png',
				deviceInfo: {}
			}
		},
		computed: {
			...mapState({
				ble: state => state.ble, // 实时蓝牙全局状态
				userInfo: state => state.userInfo,
			})
		},
		watch: {
			'ble.state': {
				handler(nVal, oVal) {
					if (nVal == 0) {
						uni.hideLoading()
						uni.showToast({
							title: '仪器已连接'
						})
					} else if (nVal == -5) {
						uni.hideLoading()
						uni.showToast({
							title: '连接超时',
							icon: 'error'
						})
					} else if (nVal == -4) {
						uni.hideLoading()
						uni.showToast({
							title: '连接失败',
							icon: 'error'
						})
					}
				}
			}
		},
		onLoad() {
			this.getBindInfo()
			this.getInfoByUser()
		},
		methods: {
			// 获取绑定信息
			async getBindInfo() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					userId: this.userId,
					urlencoded: true
				}
				try {
					const res = await getDeviceByUser(params)
					uni.hideLoading()
					if (res.data.length) {
						this.deviceInfo = res.data[0]
						this.$store.commit('setDeviceInfo', this.deviceInfo)
					} else {
						uni.redirectTo({
							url: '/pagesB/login/device/search/index'
						})
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			// 获取用户详情信息
			async getInfoByUser() {
				let params = {
					userId: this.userId,
					urlencoded: true
				}
				try {
					const res = await getDetailsByUser(params)
					if (res.code == 200) {
						this.$store.commit('setUserInfo', res.data)
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			checkBleStatus() {
				let that = this
				if (this.ble.isOpenBleAdapter) {
					wx.getBluetoothAdapterState({
						success: res => {
							if (!res.available) {
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE',
								})
							} else {
								that.connectDev()
							}
						},
						fail: err => {
							console.log(err)
							uni.showModal({
								title: '提示',
								content: '请检查蓝牙功能是否正常',
								showCancel: false
							})
						}
					})
				} else {
					wx.closeBluetoothAdapter()
					wx.openBluetoothAdapter({
						success(BleObj) {
							that.$store.commit('changeIsOpenBleAdapter', true)
							that.connectDev()
						},
						fail(err) {
							console.log('openBluetoothAdapter', err)
							if (err.errCode == 10001) {
								that.$store.commit('changeIsOpenBleAdapter', true)
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE',
								})
							}
							if (err.errMsg == 'openBluetoothAdapter:fail auth deny') {
								uni.showModal({
									title: '提示',
									content: '请先授权蓝牙权限',
									confirmColor: '#545DDE',
									success(modal_res) {
										if (modal_res.confirm) {
											wx.openSetting({
												success: (authData) => {
													if (authData.authSetting[
															'scope.bluetooth']) {
														that.checkBleStatus()
													} else { // 未授权
														uni.showModal({
															title: '提示',
															content: '授权失败,您将无法使用蓝牙相关服务',
															confirmColor: '#545DDE',
															showCancel: false,
															success(modal) {
																if (modal
																	.confirm) {
																	wx.closeBluetoothAdapter()
																	that.$store.commit(
																		'changeIsOpenBleAdapter',
																		false)
																}
															}
														})

													}
												}
											})
										} else {
											uni.showModal({
												title: '提示',
												content: '授权失败,您将无法使用蓝牙相关服务',
												confirmColor: '#545DDE',
												showCancel: false,
												success(modal) {
													if (modal.confirm) {
														wx.closeBluetoothAdapter()
														that.$store.commit(
															'changeIsOpenBleAdapter',
															false)
													}
												}
											})
										}
									}
								})
							}
						}
					})
				}
			},
			// 链接仪器
			connectDev() {
				uni.showLoading({
					title: '蓝牙连接中...'
				})
				if (uni.$u.os() == 'android') { // 安卓系统直接连接
					this.$store.commit('setDefaultInfo', {
						type: 1,
						data: {
							mac: this.deviceInfo.deviceMac,
							name: this.deviceInfo.bluetoothName
						}
					})
					BLE.common.createBLEConnectionFn(this.deviceInfo.deviceMac, this
						.deviceInfo)
				} else { // 苹果系统需要搜索uuid仪器id
					BLE.common.myStartBluetoothDevicesDiscovery(10000, this.deviceInfo)
				}
			},
			// 解绑仪器
			async unbind() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.deviceInfo.id,
					userId: this.userId,
					urlencoded: true
				}
				try {
					const res = await unbindDevice(params)
					uni.hideLoading()
					if (res.code == 200) {
						uni.showToast({
							title: '解绑成功'
						})
						this.$store.commit('resetDeviceInfo')
						setTimeout(() => {
							if (this.ble.devID) {
								wx.closeBLEConnection({
									deviceId: this.ble.devID,
									success: () => {
										console.log('断开成功')
										uni.redirectTo({
											url: '/pagesB/login/device/search/index?type=login'
										})
									}
								})
							} else {
								uni.redirectTo({
									url: '/pagesB/login/device/search/index?type=login'
								})
							}
						}, 1200)
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			async next() {
				// 未接收到电量指令之前提前发送开始测量指令
				if (!this.ble.defaultInfo.battery) return
				let params = {
					userId: this.userId
				}
				try {
					const bodyRes = await findBodyMegByUserId(params)
					const rerRes = await findFirstRer(params)
					if (bodyRes.data.off == 1 && bodyRes.data.maxExhale <= 0) {
						uni.redirectTo({
							url: '/pagesB/login/device/measure/exhale'
						})
					} else if (bodyRes.data.off == 1 && bodyRes.data.maxExhale > 0) {
						let obj = {
							estimateHaleVol: '--',
							measureData: bodyRes.data.maxExhale,
							type: 'default',
							percent: 0,
							abnormal: 0,
						}
						uni.redirectTo({
							url: `/pagesB/login/device/measure/success?info=${JSON.stringify(obj)}`
						})
					} else if (bodyRes.data.off == 0) {
						if (rerRes.data != 1) {
							uni.redirectTo({
								url: '/pagesB/login/device/measure/tips'
							})
						} else if (rerRes.data == 1) {
							uni.switchTab({
								url: '/pages/health/index'
							})
						}
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			myGetBatteryIcon(data) {
				return getBatteryIcon(data)
			}
		}
	}
</script>
<style lang="scss" scoped>
	.none {
		width: 0;
		height: 0;
	}

	.device_info {
		margin-top: 45rpx;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.title {
			font-weight: 500;
			font-size: 48rpx;
			color: #333333;
			line-height: 66rpx;
		}

		.device_c {
			margin: 80rpx 0 188rpx;
			width: 90%;
			padding: 112rpx 0 80rpx;
			background: #FAFAFA;
			border-radius: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.device_i {
				width: 120rpx;
				height: 320rpx;
			}

			.device_name {
				margin: 64rpx 0 32rpx;
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
				line-height: 44rpx;
			}

			.info {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 16rpx;
				font-size: 24rpx;
				color: #666666;

				.line {
					width: 1rpx;
					height: 24rpx;
					background-color: rgba(0, 0, 0, .1);
					margin: 0 16rpx;
				}

				.battery {
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.version {
				font-size: 24rpx;
				color: #666666;
			}
		}

		.connect_btn,
		.unbind,
		.next_step {
			width: 80%;
			height: 88rpx;
			line-height: 80rpx;
			background-color: #ffffff;
			border: 2rpx solid #1F2434;
			text-align: center;
			font-size: 36rpx;
			color: #1F2434;
			border-radius: 16rpx;
		}

		.unbind {
			margin-top: 32rpx;
			background-color: #1F2434;
			color: #FFFFFF;
			border: 0;
			line-height: 88rpx;
		}
	}
</style>